// stores/auth.store.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
    const router = useRouter()

    // 状态
    const user = ref(null)
    const token = ref(localStorage.getItem('token') || null)
    const isAuthenticated = computed(() => !!token.value)
    const loading = ref(false)
    const error = ref(null)
    const isAdmin = computed(() => user.value?.userType === 'ADMIN')
    const isTeacher = computed(() => user.value?.userType === 'TEACHER')
    const isStudent = computed(() => user.value?.userType === 'STUDENT')

    // 初始化时尝试获取用户信息
    const initialize = async () => {
        if (token.value && !user.value) {
            try {
                await fetchUser()
            } catch (err) {
                clearAuth()
            }
        }
    }

    // 登录
    const login = async (credentials) => {
        try {
            loading.value = true
            error.value = null

            const response = await api.post('/auth/login', credentials)

            if (response.data.token) {
                token.value = response.data.token
                localStorage.setItem('token', token.value)

                await fetchUser()

                // 根据用户类型跳转到不同页面
                const redirectPath = getRedirectPath()
                router.push(redirectPath)

                return true
            }

            return false
        } catch (err) {
            error.value = err.response?.data?.message || err.message || '登录失败'
            ElMessage.error(error.value)
            return false
        } finally {
            loading.value = false
        }
    }

    // 获取用户信息
    const fetchUser = async () => {
        try {
            const response = await api.get('/user/me')
            user.value = response.data
            return user.value
        } catch (err) {
            clearAuth()
            throw err
        }
    }

    // 登出
    const logout = async () => {
        try {
            await api.post('/auth/logout')
        } catch (err) {
            console.error('登出时出错:', err)
        } finally {
            clearAuth()
            router.push({ name: 'Login' })
        }
    }

    // 修改密码
    const changePassword = async (data) => {
        try {
            loading.value = true
            error.value = null

            const response = await api.put('/user/password', data)

            if (response.data.success) {
                ElMessage.success('密码修改成功')

                // 密码修改后强制重新登录
                await logout()
                router.push({ name: 'Login', query: { redirect: router.currentRoute.value.fullPath } })

                return true
            }

            return false
        } catch (err) {
            error.value = err.response?.data?.message || err.message || '密码修改失败'
            ElMessage.error(error.value)
            return false
        } finally {
            loading.value = false
        }
    }

    // 重置密码（管理员操作用户密码）
    const resetUserPassword = async (userId, newPassword) => {
        try {
            loading.value = true
            const response = await api.put(`/admin/users/${userId}/password`, { newPassword })
            return response.data.success
        } catch (err) {
            error.value = err.response?.data?.message || err.message || '重置密码失败'
            ElMessage.error(error.value)
            return false
        } finally {
            loading.value = false
        }
    }

    // 清除认证信息
    const clearAuth = () => {
        token.value = null
        user.value = null
        localStorage.removeItem('token')
    }

    // 获取用户重定向路径
    const getRedirectPath = () => {
        if (!user.value) return '/'

        switch (user.value.userType) {
            case 'ADMIN':
                return '/admin/dashboard'
            case 'TEACHER':
                return '/research/projects'
            case 'STUDENT':
                return '/student/dashboard'
            default:
                return '/'
        }
    }

    // 设置请求头中的token
    const setAuthHeader = () => {
        if (token.value) {
            api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
        } else {
            delete api.defaults.headers.common['Authorization']
        }
    }

    // 监听token变化自动设置请求头
    watch(token, () => {
        setAuthHeader()
    }, { immediate: true })

    // 初始化
    initialize()

    return {
        // 状态
        user,
        token,
        isAuthenticated,
        loading,
        error,
        isAdmin,
        isTeacher,
        isStudent,

        // 方法
        login,
        logout,
        fetchUser,
        changePassword,
        resetUserPassword,
        clearAuth,
        initialize
    }
})